package com.jmpt.fangbohui.ui.personalcenter;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.jmpt.fangbohui.Constants;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.adapter.ManageHouseListAdapter;
import com.jmpt.fangbohui.adapter.ManageHouseListAdapter.OnDeleteListCheckListener;
import com.jmpt.fangbohui.bean.AlreadyBBClientBean;
import com.jmpt.fangbohui.bean.ManagerHouseBean;
import com.jmpt.fangbohui.bean.ManagerHouseBean.ho_houseList;
import com.jmpt.fangbohui.dao.LoginSQLiteOperator;
import com.jmpt.fangbohui.ui.base.BaseActivity;
import com.jmpt.fangbohui.ui.base.BaseHeadActivity;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.ToastHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class ManageHouseActivity extends BaseHeadActivity implements  OnClickListener 
{

	public final static int SUCCESS = 200;
	public final static int FAILED = 202;
	private boolean isDelete = false;
	public final static int BATCH_SUCCESS = 12;
	public final static int BATCH_FAILED = 13;
	public final static int PARSERS = 14;
	private int type  = 1; //1 删除  2 发布  3待发布

	private Handler handler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			lv_activity_manage_house.onRefreshComplete();
			hideLoading();
			switch (msg.what)
			{
			case SUCCESS:
				refreshListView();
				break;
			case FAILED:
				String str2 = (String) msg.obj;
				ToastHelper.ShowToast(str2, mContext);
				ll_manage_house_btn_container.setVisibility(View.GONE);
				btn_manage_house_cancel.setVisibility(View.GONE);
				btn_manage_house_ok.setVisibility(View.GONE);
				lv_activity_manage_house.setVisibility(View.GONE);
				hideLoading();
				break;
			case 321:
				lv_activity_manage_house.onRefreshComplete();
				break;

			case BATCH_SUCCESS:
				firstLoad();
				String str3 = (String) msg.obj;
				ToastHelper.ShowToast(str3, mContext);
				break;
			case BATCH_FAILED:
				ToastHelper.ShowToast("网络不畅通，请稍后再试", mContext);
				hideLoading();
				break;
			case PARSERS:
				String string = (String) msg.obj;
				DebugLog.i(string);
				Gson gson = new Gson();
				ManagerHouseBean fromJson = gson.fromJson(string, ManagerHouseBean.class);
				ToastHelper.ShowToast(fromJson.msg, ManageHouseActivity.this);
				break;
			}

		};
	};
	private ManagerHouseBean bean;
	private com.handmark.pulltorefresh.library.PullToRefreshListView lv_activity_manage_house;
	private TextView tv_manage_house;
	private Button btn_manage_house_ok;
	private Button btn_manage_house_cancel;
	private Button btn_manage_house_delete;
	private ManageHouseListAdapter mAdapter;
	private boolean isNoMore = false;
	private boolean isFirstLoad = true;
	
	//搜索关键字
	private String queryContext = "";
	
	//当前访问的页面编号
	private int currentPage = 1;
	private List<ho_houseList> mData;
	private EditText et_manage_house_query_context;
	private Button btn_manage_house_query;
	private Button btn_manage_house_publish;
	private Button btn_manage_house_unpublish;
	private LinearLayout ll_manage_house_btn_container;
	private Button btn_manage_house_refresh;
	
	private String current_houseid = "";

	private AlertDialog show;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		initView();
		initData();
	}


	protected void refreshListView()
	{
		if(bean.retval == null){
			emptyData();
			return;
		}
		if(isFirstLoad){
			mData = bean.retval.ho_houseList;
		}else{
			mData.addAll(bean.retval.ho_houseList);
		}
		if(mData == null || mData.size() ==0){
			emptyData();
			return;
		}
			mAdapter = new ManageHouseListAdapter(this,mData,isDelete);
			lv_activity_manage_house.setAdapter(mAdapter);
			mAdapter.notifyDataSetChanged();
		hasData();
//		mAdapter.setOnDeleteListCheckListener(this);
	}

	private void initData()
	{
		LoginSQLiteOperator oper = new LoginSQLiteOperator(this);
		final List<String> querySessionId = oper.querySessionId();
		if (querySessionId.size() != 2)
		{
			return;
		}
		showLoading();

		new Thread()
		{
			public void run()
			{
				HttpClient httpClient = new DefaultHttpClient();
				try
				{
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("AgentId", querySessionId
							.get(0)));

					HttpPost postMethod = new HttpPost(
							Constants.URL.MANAGER_HOUSE+"?p="+currentPage +"&k="+queryContext);
					postMethod.setHeader("Cookie", "PHPSESSID="
							+ querySessionId.get(1));
					postMethod.setEntity(new UrlEncodedFormEntity(params,
							"utf-8")); // 将参数填入POST Entity中

					HttpResponse response = httpClient.execute(postMethod); // 执行POST方法
					DebugLog.i("currentPage = "
							+ currentPage);

					if (response.getStatusLine().getStatusCode() != 200)
					{
						Message msg = Message.obtain();
						msg.what = FAILED;
						msg.obj = "网络暂不畅通，请稍后再试";
						handler.sendMessage(msg);
						return;
					}
					parser(EntityUtils.toString(response.getEntity(), "utf-8"));

				} catch (Exception e)
				{
					e.printStackTrace();
				}
			};
		}.start();
	}
	private void emptyData(){
		tv_manage_house.setVisibility(View.VISIBLE);
		lv_activity_manage_house.setVisibility(View.INVISIBLE);
		ll_manage_house_btn_container.setVisibility(View.GONE);
	}
	private void hasData(){
		tv_manage_house.setVisibility(View.INVISIBLE);
		lv_activity_manage_house.setVisibility(View.VISIBLE);
		ll_manage_house_btn_container.setVisibility(View.VISIBLE);
		
	}
	private void parser(String str)
	{
		Gson gson = new Gson();
		str = str.substring(str.indexOf("{"));
		DebugLog.i(str);
		bean = gson.fromJson(str, ManagerHouseBean.class);
		if(Boolean.parseBoolean(bean.done)){
			int pageIndex = Integer.parseInt(bean.retval.pageInfo.pageIndex);
			int pageCount = Integer.parseInt(bean.retval.pageInfo.pageCount);
			if(pageCount == pageIndex){
				isNoMore = true;
			}else{
				isNoMore = false;
			}
			Message msg = Message.obtain();
			msg.what = SUCCESS;
			msg.obj = bean.msg;
			handler.sendMessage(msg);
		}else{
			Message msg = Message.obtain();
			msg.what = FAILED;
			msg.obj = bean.msg;
			handler.sendMessage(msg);
		}
	}

	private void initView()
	{
		setContentView(R.layout.activity_manage_house);
		showTitle("房源管理");
		showBackButton(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		lv_activity_manage_house = (com.handmark.pulltorefresh.library.PullToRefreshListView) findViewById(R.id.lv_activity_manage_house);
		tv_manage_house = (TextView) findViewById(R.id.tv_manage_house);
		btn_manage_house_ok = (Button) findViewById(R.id.btn_manage_house_ok);
		btn_manage_house_cancel = (Button) findViewById(R.id.btn_manage_house_cancel);
		btn_manage_house_delete = (Button) findViewById(R.id.btn_manage_house_delete);
		ll_manage_house_btn_container = (LinearLayout) findViewById(R.id.ll_manage_house_btn_container);
		
		et_manage_house_query_context = (EditText) findViewById(R.id.et_manage_house_query_context);
		TextWatcher tw = new TextWatcher(){

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after)
			{
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count)
			{
				queryContext = s.toString();
			}

			@Override
			public void afterTextChanged(Editable s)
			{
				
			}};
		et_manage_house_query_context.addTextChangedListener(tw);
		
		btn_manage_house_query = (Button) findViewById(R.id.btn_manage_house_query);
		btn_manage_house_publish = (Button) findViewById(R.id.btn_manage_house_publish);
		btn_manage_house_unpublish = (Button) findViewById(R.id.btn_manage_house_unpublish);
		btn_manage_house_refresh = (Button) findViewById(R.id.btn_manage_house_refresh);
		btn_manage_house_ok.setOnClickListener(this);
		btn_manage_house_cancel.setOnClickListener(this);
		btn_manage_house_refresh.setOnClickListener(this);
		btn_manage_house_delete.setOnClickListener(this);
		btn_manage_house_query.setOnClickListener(this);
		btn_manage_house_publish.setOnClickListener(this);
		btn_manage_house_unpublish.setOnClickListener(this);
		lv_activity_manage_house.setMode(PullToRefreshBase.Mode.BOTH);
		lv_activity_manage_house.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				firstLoad();
			}
			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				if(isNoMore){
					ToastHelper.ShowToast("没有更多数据了", getApplicationContext());
					Message obtain = Message.obtain();
					handler.sendMessage(obtain);
				}else{
					// 加载更多
					loadMore();
				}
			}
		});
	}

	public void firstLoad(){
		isFirstLoad = true;
		currentPage = 1;
		initData();
	}
	public void loadMore(){
		isFirstLoad = false;
		currentPage++;
		initData();
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.btn_manage_house_delete:
			clickDelete();
			break;
		case R.id.btn_manage_house_publish:
			clickPublish();
			break;
		case R.id.btn_manage_house_unpublish:
			clickUnPublish();
			break;
		case R.id.btn_manage_house_refresh:
			clickRefresh();
			break;
		case R.id.btn_manage_house_ok:
			clickOk();
			break;
		case R.id.btn_manage_house_cancel:
			clickCancel();
			break;
		case R.id.btn_manage_house_query:
			firstLoad();
			break;
		}
	}
	
	private void clickCancel() {
		showDeleteButton();
		mAdapter.setDeleteStatus();
	}

	private void clickOk() {
		String houseIDs = mAdapter.showDeletePosition();
		if(type == 1){
			batchDeleteHouse(houseIDs,Constants.URL.BATCHDELETEHOUSE);
		}else if(type == 2){
			batchDeleteHouse(houseIDs,Constants.URL.BATCHPUBLISH);
		}else if(type == 3){
			batchDeleteHouse(houseIDs,Constants.URL.BATCHUNPUBLISH);
		}else if(type ==4 ){
			batchDeleteHouse(houseIDs,Constants.URL.BATCHREFRESH);
		}
		showDeleteButton();
		mAdapter.setDeleteStatus();
	}

	private void clickDelete() {	
		type = 1;
		showOkCanCelButton();
		mAdapter.setDeleteStatus();
	}	
	private void clickPublish() {	
		type = 2;
		showOkCanCelButton();
		mAdapter.setDeleteStatus();
	}	
	private void clickUnPublish() {	
		type = 3;
		showOkCanCelButton();
		mAdapter.setDeleteStatus();
	}	
	private void clickRefresh() {	
		type = 4;
		showOkCanCelButton();
		mAdapter.setDeleteStatus();
	}	
	private void showDeleteButton(){	
		ll_manage_house_btn_container.setVisibility(View.VISIBLE);
		btn_manage_house_cancel.setVisibility(View.INVISIBLE);
		btn_manage_house_ok.setVisibility(View.INVISIBLE);
	}
	
	private void showOkCanCelButton(){
		ll_manage_house_btn_container.setVisibility(View.INVISIBLE);
		btn_manage_house_cancel.setVisibility(View.VISIBLE);
		btn_manage_house_ok.setVisibility(View.VISIBLE);
		
	}
	
	public void operatorHouse(final String HouseID,final String url){
		showLoading();
		LoginSQLiteOperator oper = new LoginSQLiteOperator(mContext);
		final List<String> querySessionId = oper.querySessionId();
		if(querySessionId.size() != 2){
			return;
		}
		
		new Thread(){
			public void run() {
				HttpClient httpClient = new DefaultHttpClient();
				try {
					
				    HttpGet postMethod = new HttpGet(url+"?HouseID=" +HouseID);
				    postMethod.setHeader("Cookie", "PHPSESSID=" + querySessionId.get(1)); 
				    HttpResponse response = httpClient.execute(postMethod); //执行GET方法
				    DebugLog.i("resCode = " + response.getStatusLine().getStatusCode());
				    
				    if(response.getStatusLine().getStatusCode() != 200){
				    	return;
				    }
				    parsers(EntityUtils.toString(response.getEntity(), "utf-8"));
				    
								
				} catch (Exception e) {
				    e.printStackTrace();
				} 
			};
		}.start();
	}
	
	protected void parsers(String string)
	{
		Message obtain = Message.obtain();
		obtain.obj = string;
		obtain.what = PARSERS;
		handler.sendMessage(obtain);
	}

	public void batchDeleteHouse(final String HouseIDs,final String url){
		showLoading();
		LoginSQLiteOperator oper = new LoginSQLiteOperator(mContext);
		final List<String> querySessionId = oper.querySessionId();
		if(querySessionId.size() != 2){
			return;
		}
		new Thread(){
			public void run() {
				HttpClient httpClient = new DefaultHttpClient();
				try {
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("HouseIDs",HouseIDs));
					DebugLog.i(HouseIDs);
					
				    HttpPost postMethod = new HttpPost(url);
				    postMethod.setHeader("Cookie", "PHPSESSID=" + querySessionId.get(1)); 
				    postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中
								
				    HttpResponse response = httpClient.execute(postMethod); //执行POST方法
				    DebugLog.i("resCode = " + response.getStatusLine().getStatusCode());
				    
				    if(response.getStatusLine().getStatusCode() != 200){
				    	Message msg = Message.obtain();
					    msg.what = BATCH_FAILED;
					    msg.obj = "网络暂不畅通，请稍后再试";
					    handler.sendMessage(msg);
				    	return;
				    }
				    parserBatc0hDeleteHouse(EntityUtils.toString(response.getEntity(), "utf-8"));
				    
								
				} catch (Exception e) {
				    e.printStackTrace();
				} 
			}

		}.start();
	}

	protected void parserBatc0hDeleteHouse(String string) {
		DebugLog.i(string);
		Gson gson = new Gson();
		ManagerHouseBean fromJson = gson.fromJson(string, ManagerHouseBean.class);
		Message msg = Message.obtain();
	    msg.what = BATCH_SUCCESS;
	    msg.obj = fromJson.msg;
	    handler.sendMessage(msg);
	}
}
